package com.atguigu.tingshu;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.query.search.AlbumInfoIndex;

import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.album.AlbumListVo;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class ServiceSearchApplicationTest {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Test
    void  test02(){
        // 索引库的初始化
        IndexOperations indexOps = this.elasticsearchTemplate.indexOps(AlbumInfoIndex.class);
        if (!indexOps.exists()) {
            indexOps.create();
            indexOps.putMapping();
        }

        // 提示词库的初始化
        IndexOperations indexOps2 = this.elasticsearchTemplate.indexOps(SuggestIndex.class);
        if (!indexOps2.exists()){
            indexOps2.create();
            indexOps2.putMapping();
        }

        Integer pageNum = 1;
        Integer pageSize = 100;
        do {
            // 分批查询专辑
            Result<List<AlbumListVo>> albumPageResult = this.albumInfoFeignClient.findAlbumPage(pageNum, pageSize);
            Assert.notNull(albumPageResult, "数据导入时，分片查询专辑失败！");
//        if (albumPageResult == null){
//            throw new RuntimeException("数据导入时，分片查询专辑失败！");
//        }
            List<AlbumListVo> albumListVos = albumPageResult.getData();
            if (CollectionUtils.isEmpty(albumListVos)){
                return;
            }
            albumListVos.forEach(albumListVo -> {
                AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
                BeanUtils.copyProperties(albumListVo, albumInfoIndex);
                albumInfoIndex.setId(albumListVo.getAlbumId());
                // 根据主播id查询主播
                Result<UserInfo> userInfoResult = this.userInfoFeignClient.getUserInfoById(albumListVo.getUserId());
                Assert.notNull(userInfoResult, "数据导入时，获取用户信息失败！");
                UserInfo userInfo = userInfoResult.getData();
                if (userInfo != null){
                    albumInfoIndex.setAnnouncerName(userInfo.getNickname());
                }

                // 根据三级分类id查询一二三级分类
                Result<BaseCategoryView> baseCategoryViewResult = this.categoryFeignClient.getBaseCategoryViewBycategory3Id(albumListVo.getCategory3Id());
                Assert.notNull(baseCategoryViewResult, "数据导入时，获取三级分类信息失败！");
                BaseCategoryView baseCategoryView = baseCategoryViewResult.getData();
                if (baseCategoryView != null) {
                    albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
                    albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
                }

                // 伪造数据
                albumInfoIndex.setPlayStatNum(new Random().nextInt(10) * 1000000);
                albumInfoIndex.setSubscribeStatNum(new Random().nextInt(10) * 1000000);
                albumInfoIndex.setBuyStatNum(new Random().nextInt(10) * 1000000);
                albumInfoIndex.setCommentStatNum(new Random().nextInt(10) * 1000000);
                albumInfoIndex.setHotScore(albumInfoIndex.getPlayStatNum() * 0.1
                        + albumInfoIndex.getSubscribeStatNum() * 0.3 + albumInfoIndex.getCommentStatNum() * 0.2
                        + albumInfoIndex.getBuyStatNum() * 0.4);

                // 属性信息
                Result<List<AlbumAttributeValue>> albumAttributeValuesResult = this.albumInfoFeignClient.findAlbumAttributesByAlbumId(albumListVo.getAlbumId());
                Assert.notNull(albumAttributeValuesResult, "数据导入时，获取专辑标签值失败！" + albumListVo.getAlbumId());
                List<AlbumAttributeValue> albumAttributeValues = albumAttributeValuesResult.getData();
                if (!CollectionUtils.isEmpty(albumAttributeValues)){
                    // 把AlbumAttributeValue集合转化成AttributeValueIndex集合
                    List<AttributeValueIndex> attributeValueIndexList =  albumAttributeValues.stream().map(albumAttributeValue -> {
                        AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                        BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                        return attributeValueIndex;
                    }).collect(Collectors.toList());
                    albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);
                }
                this.elasticsearchTemplate.save(albumInfoIndex);

                // 向提示词库新增数据
                SuggestIndex titleSuggestIndex = new SuggestIndex();
                titleSuggestIndex.setId("album_" + albumListVo.getAlbumId());
                titleSuggestIndex.setTitle(albumListVo.getAlbumTitle());
                titleSuggestIndex.setKeyword(new Completion(List.of(albumListVo.getAlbumTitle())));
                titleSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumTitle()))));
                titleSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.getFirstLetter(albumListVo.getAlbumTitle()))));
                this.elasticsearchTemplate.save(titleSuggestIndex);

                SuggestIndex introSuggestIndex = new SuggestIndex();
                introSuggestIndex.setId("intro_" + albumListVo.getAlbumId());
                introSuggestIndex.setTitle(albumListVo.getAlbumIntro());
                introSuggestIndex.setKeyword(new Completion(List.of(albumListVo.getAlbumIntro())));
                introSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumIntro()))));
                introSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.getFirstLetter(albumListVo.getAlbumIntro()))));
                this.elasticsearchTemplate.save(introSuggestIndex);

                if (userInfo != null){
                    SuggestIndex annoucerSuggestIndex = new SuggestIndex();
                    annoucerSuggestIndex.setId("announcer_" + userInfo.getId());
                    annoucerSuggestIndex.setTitle(userInfo.getNickname());
                    annoucerSuggestIndex.setKeyword(new Completion(List.of(userInfo.getNickname())));
                    annoucerSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(userInfo.getNickname()))));
                    annoucerSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.getFirstLetter(userInfo.getNickname()))));
                    this.elasticsearchTemplate.save(annoucerSuggestIndex);
                }
            });

            // 下一页
            pageSize = albumListVos.size();
            pageNum++;
        } while (pageSize == 100);

    }


    @Test
    void test01(){
        //索引库优化
        IndexOperations indexOperations = this.elasticsearchTemplate.indexOps(AlbumInfoIndex.class);
        if (!indexOperations.exists()){
            indexOperations.create();
            indexOperations.putMapping();
        }
        //提示词库的初始化
        IndexOperations indexOperations2 = this.elasticsearchTemplate.indexOps(SuggestIndex.class);
        if (!indexOperations2.exists()){
            indexOperations2.create();
            indexOperations2.putMapping();
        }


        //分批查询

        Integer pageNum = 1;
        Integer pageSize=100;


        do {
            Result<List<AlbumListVo>> albumPage = this.albumInfoFeignClient.findAlbumPage(pageNum, pageSize);
            if (albumPage==null){
                throw new RuntimeException("数据导入远程调用 分片查询专辑失败!!!!");
            }
            List<AlbumListVo> albumListVos = albumPage.getData();

            if (CollectionUtils.isEmpty(albumListVos)){
                return;
            }

            albumListVos.forEach(albumListVo -> {

                AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
                BeanUtils.copyProperties(albumListVo,albumInfoIndex);
                albumInfoIndex.setId(albumListVo.getAlbumId());

                    //根据主播id查询主播
                Result<UserInfo> userInfoById = userInfoFeignClient.getUserInfoById(albumListVo.getUserId());


                if (userInfoById==null){
                    throw new RuntimeException("远程调用根据主播id查询用户信息失败");
                }
                if (userInfoById.getData()!=null){

                    albumInfoIndex.setAnnouncerName(userInfoById.getData().getNickname());
                }


                //查询三级分类id
                Result<BaseCategoryView> baseCategoryViewBycategory3Id = categoryFeignClient.getBaseCategoryViewBycategory3Id(albumListVo.getCategory3Id());
               if (baseCategoryViewBycategory3Id==null){
                   throw new RuntimeException("远程嗲用查询三级分类信息失败");
               }

                BaseCategoryView baseCategoryView = baseCategoryViewBycategory3Id.getData();

               if (baseCategoryView!=null){
                   albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
                    albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
               }

               //假数据
                albumInfoIndex.setPlayStatNum(new Random().nextInt(10)*10000);
                albumInfoIndex.setSubscribeStatNum(new Random().nextInt(10)*10000);
                albumInfoIndex.setBuyStatNum(new Random().nextInt(10)*10000);

                albumInfoIndex.setHotScore(albumInfoIndex.getPlayStatNum()*0.1
                        +albumInfoIndex.getSubscribeStatNum()*0.3
                        +albumInfoIndex.getCommentStatNum()*0.2
                        +albumInfoIndex.getBuyStatNum()*0.4);


                //标签属性
                Result<List<AlbumAttributeValue>> albumAttributesByAlbumId = this.albumInfoFeignClient.findAlbumAttributesByAlbumId(albumListVo.getAlbumId());
                if (albumAttributesByAlbumId==null){
                    throw new RuntimeException("远程调用查询标签数据失败");

                }
                List<AlbumAttributeValue> albumAttributeValues = albumAttributesByAlbumId.getData();
                if (albumAttributeValues!=null){
                    List<AttributeValueIndex> attributeValueIndexList = albumAttributeValues.stream().map(albumAttributeValue -> {
                        AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                        BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                        return attributeValueIndex;
                    }).collect(Collectors.toList());

                    //设置给albumInfoIndex
                    albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);

                }


                this.elasticsearchTemplate.save(albumInfoIndex);

                //向提示词库新增数据
                if (StringUtils.isNotBlank(albumListVo.getAlbumTitle())) {
                    SuggestIndex titleSuggestIndex = new SuggestIndex();
                    titleSuggestIndex.setId("album_" + albumListVo.getAlbumId());
                    titleSuggestIndex.setKeyword(new Completion(List.of(albumListVo.getAlbumTitle())));
                    titleSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumTitle()))));
                    titleSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumTitle()))));
                    titleSuggestIndex.setTitle(albumListVo.getAlbumTitle());
                    this.elasticsearchTemplate.save(titleSuggestIndex);
                }
                if (StringUtils.isNotBlank(albumListVo.getAlbumIntro())){

                    SuggestIndex IntroSuggestIndex = new SuggestIndex();
                    IntroSuggestIndex.setId("Intro_"+albumListVo.getAlbumId());
                    IntroSuggestIndex.setKeyword(new Completion(List.of(albumListVo.getAlbumIntro())));
                    IntroSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumIntro()))));
                    IntroSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.toHanyuPinyin(albumListVo.getAlbumIntro()))));
                    IntroSuggestIndex.setTitle(albumListVo.getAlbumTitle());
                    this.elasticsearchTemplate.save(IntroSuggestIndex);
                }

                if (userInfoById!=null){

                    SuggestIndex annoucerSuggestIndex = new SuggestIndex();
                    annoucerSuggestIndex.setId("annoucer_"+userInfoById.getData().getNickname());
                    annoucerSuggestIndex.setKeyword(new Completion(List.of(userInfoById.getData().getNickname())));
                    annoucerSuggestIndex.setKeywordPinyin(new Completion(List.of(PinYinUtils.toHanyuPinyin(userInfoById.getData().getNickname()))));
                    annoucerSuggestIndex.setKeywordSequence(new Completion(List.of(PinYinUtils.toHanyuPinyin(userInfoById.getData().getNickname()))));
                    annoucerSuggestIndex.setTitle(albumListVo.getAlbumTitle());
                    this.elasticsearchTemplate.save(annoucerSuggestIndex);
                }


            });
            pageNum++;
            pageSize=albumListVos.size();

        }while (pageSize==100);



    }



}